requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        jquery: 'jquery.min',
        jquery_route: 'jquery.route',
        bootstrap: "../../bootstrap-3.3.5/dist/js/bootstrap.min",
        bootstrap_paginator:"../plugins/bootstrap-paginator/bootstrap-paginator",
        validform:"../plugins/Validform/Validform_v5.3.2",
        config: "../common/config",
        common: "../common/common",
        arttemplateUtil: '../common/arttemplate-util',
        stringUtil: "../common/string-util",
        task:"../common/task",
        pageJs: '../common/pageJs',
        commonUtil: '../common/common-util',
        goodsCommon:"../modules/goods/goods_common"
    },
    shim: { //引入没有使用requirejs模块写法的类库。backbone依赖underscore
        'jquery': {
            exports: '$'
        },
        'bootstrap': ['jquery'],
        'bootstrap_paginator':{
        	deps:['bootstrap'],
        	exports: 'bootstrp'
        }
    }
});
requirejs(['jquery', 'pageJs','config', 'common','arttemplateUtil','stringUtil','task','validform','commonUtil','goodsCommon','msg_util','jquery_qrcode'], function($, pageJs,config,common,arttemplateUtil,stringUtil,task,validform,commonUtil,goodsCommon,msg_util) {
	
	var queryStatus = false;//是否需要传入查询参数
	var goodslist_tpl;//订单列表模板
	var goodssort_tpl;//排序列表模板
	
	var initTpl = function(){
		goodslist_tpl = arttemplateUtil.template.compile($.setHTML('goods/templates/goods_sale_list_tpl.html'));
		goodssort_tpl = arttemplateUtil.template.compile($.setHTML('goods/templates/goodssort_tpl.html'));
	}
	
	//获取查询时需要的参数
	var getQueryFormParams = function() {
		var formParam = {};
		formParam.goods_id = $("input[name=goods_id]").val();
		formParam.goods_name = $("input[name=goods_name]").val();
		formParam.beginpric = $("input[name=beginpric]").val();
		formParam.endpric = $("input[name=endpric]").val();
		formParam.beginnum = $("input[name=beginnum]").val();
		formParam.endnum = $("input[name=endnum]").val();
		formParam.msgflag = $("input[name=msgflag]").prop("checked");
		return formParam;
	}
	
	//分页查找商品列表信息
	var queryGoodsPageList = function(page,initQueryParam) {
		var index = common.loading();
		var params = initQueryParam;
		
		//查询表单入参
		if(queryStatus) {
			params = getQueryFormParams();
		}
		params.pageNo = page;
		common.common_ajax_request('/api/v1/queryPageSaleOfGoodsMsgList', params, false, function(data){
			//如果第一次进入页面，url地址存在参数，则给出提示
			if(params.flag && data.totalCount==0) {
				window.layer.msg('该商品已下架或不存在!');
			} 
			data.url=config.imgRoot();
			//渲染商品列表信息开始
			$("#goods_list_content").html(goodslist_tpl(data));
			pageJs.setPage(data.pageNo,data.totalPage,data.totalCount,callback);
			window.layer.close(index);
		},'','post');
	}
	
	//分页查找信息服务端成功返回后执行的操作
	var callback = function(page,params){
		queryGoodsPageList(page,{});
	}
	
	var initGoodsPageList = function() {
		var initQueryParam = {};
		//获取url地址入参
		if(stringUtil.isNotEmpty($("input[name=goods_id]").val())) {
			initQueryParam.goods_id = $("input[name=goods_id]").val();
			initQueryParam.flag = true;
		}
		queryGoodsPageList(1,initQueryParam);
	}
	
	//商品下架功能
	var goodsOnShelve = function(mulitId) {
		if(mulitId != "") {
			task.openConfirmTask('确定下架商品?',function() {
				//点击"确认"按钮响应事件
				common.common_ajax_request('/api/v1/goodsSelf.htm',{
					mulitId:mulitId,
					flag:"2"
				}, false, function(data,code,businessMsg){
					if(businessMsg.businessCode == 0) {
						//刷新商品列表信息
						loadData();
						window.layer.msg("下架成功，需要查看，前往仓库中的商品");
					} else {
						//刷新商品列表信息
						loadData();
						window.layer.msg(businessMsg.businessNote);
					}
				});
			});
		} else {
			task.modal_alert("请至少选择一条数据记录");
			return;
		}
	}
	
	//点击上方可以多选的下架按钮响应
	var goodsMulitIdDownShelveBtnClick = function() {
		$(document).off('click',"#goods_down_shelve").on('click',"#goods_down_shelve",function() {
			var mulitId="";
			$(":checkbox[name='goods_check']:checked").each(function(){
			  if($(this).val()!=""){	  
			    mulitId=mulitId+$(this).val()+",";
			  }
			});
			goodsOnShelve(mulitId);
			//a标签的点击事件要加个返回值，false时禁用到点击时控件随机的链接跳转
			return false;
		});
	}
	
	//点击商品列表中单个商品的下架按钮响应事件
	var goodsSigleDownShelveBtnClick = function() {
		$(document).off('click',".goods_single_down_shelve").on('click',".goods_single_down_shelve",function() {
			//获取商品id
			var goodsId = $(this).attr("data-id");
			goodsOnShelve(goodsId);
		});
	}
	
	//点击商品列表中商品推荐按钮响应事件
	var goodsRecommendBtnClick = function(obj) {
		$(document).off('click',obj).on('click',obj,function() {
			//获取商品id
			var goodsId = $(this).attr("data-goods-id");
			var dataFlag = $(this).attr("data-flag");
			var origThis = $(this);
			var recommend = false;
			var titletip = "确定取消推荐商品?"
			if(dataFlag == "0") {
				recommend= true;
				titletip = "确定推荐商品?";
			}
			task.openConfirmTask(titletip,function() {
				//点击"确认"按钮响应事件
				common.common_ajax_request('/api/v1/goodsRecommend',{
					goodsId:goodsId,
					isRecommend:recommend
				}, false, function(data,code,businessMsg){
					if(code == "200") {
						//刷新商品列表信息
						if(dataFlag == "0") {
							origThis.html("取消推荐");
							origThis.attr("data-flag","1");
						} else {
							origThis.html("推荐");
							origThis.attr("data-flag","0");
						}
					} else {
						task.modal_alert(businessMsg.businessNote);
					}
				});
			});
			
		});
		return;
	}
	
	
	var query_demo = $("#query_form").Validform({
		tiptype:3,
		isShowRight:false,
		datatype: {
			"saleCompare": function(gets,obj,curform,regxp){ //销量比较
				var minsale = $("input[name=beginnum]").val();
				var maxsale = $("input[name=endnum]").val();
				var reg = /^[1-9]\d{0,8}$|^0$/;
				if((stringUtil.isNotEmpty(minsale) && !reg.test(minsale)) || (stringUtil.isNotEmpty(maxsale) && !reg.test(maxsale))) {
					return "请输入[0-999999999]整数";
				}
				
				if(stringUtil.isNotEmpty(minsale) && stringUtil.isNotEmpty(maxsale)) {
					if (parseInt(maxsale) < parseInt(minsale)) {
						return "总销量区间范围错误";
					}
				}
				$("input[name=beginnum]").removeClass("Validform_error");
				$("input[name=endnum]").removeClass("Validform_error");
				return true;
			},"priceCompare": function(gets,obj,curform,regxp){ //销量比较
				var minPrice = $("input[name=beginpric]").val();
				var maxPrice = $("input[name=endpric]").val();
				
				if((stringUtil.isNotEmpty(minPrice) && !commonUtil.isPrice(minPrice)) || (stringUtil.isNotEmpty(maxPrice) && !commonUtil.isPrice(maxPrice))) {
					return "格式错误,价格范围在【0-99999.99】";
				}
				
				if(stringUtil.isNotEmpty(minPrice) && stringUtil.isNotEmpty(maxPrice)) {
					if (parseFloat(maxPrice) < parseFloat(minPrice)) {
						return "当前价格区间范围错误";
					}
				}
				$("input[name=beginpric]").removeClass("Validform_error");
				$("input[name=endpric]").removeClass("Validform_error");
				return true;
			}
        }
	});
	
	//商品搜索方法
	var goodsSearch = function() {
		queryStatus = true;
		queryGoodsPageList(1,{});
		return false;
	}
	
	//搜索按钮响应事件
	var goodsSearchBtnClick = function() {
		$("#search_btn").on("click",function(){
			//表单验证通过，执行搜索操作
			if(query_demo.check()) {
				goodsSearch();
			}
			return;
		});
	}
	
	//查询条件重置按钮响应
	var resetBtnClick = function() {
		$("#reset_btn").on("click",function(){
			$("input[name=goods_id]").val('');
			$("input[name=goods_name]").val('');
			$("input[name=beginpric]").val('');
			$("input[name=endpric]").val('');
			$("input[name=beginnum]").val('');
			$("input[name=endnum]").val('');
			$("input[name=msgflag]").prop("checked",false);
			//$(this).attr("type","reset");
			$("#query_form input").removeClass("Validform_error");
			$("#query_form .Validform_checktip ").html("").removeClass("Validform_wrong");
			//条件重置完要重新更新商品列表
			goodsSearch();
			queryStatus = false;
			return false;
		});
	}
	
	var loadData = function() {
		var currentPage = $("#page").find(".active").find("a").html();
		queryGoodsPageList(currentPage,{});
	}
	
	/***********************************************点击删除按钮删除商品*********************************/
	var goodsDeleteBtnClick = function() {
		//先解除绑定，保证每次只绑定一次
		$(document).off('click',"#goods_remove").on('click',"#goods_remove",function() {
			var mulitId="";
			$(":checkbox[name='goods_check']:checked").each(function(){
			  if($(this).val()!=""){
			    mulitId=mulitId+$(this).val()+",";
			  }
			});
			if(mulitId != "") {
				task.openConfirmTask('确认删除商品?',function() {
					//点击"确认"按钮响应事件
					common.common_ajax_request('/api/v1/goodsDel.htm',{
						mulitId:mulitId
					}, false, function(data,code,businessMsg){
						if(businessMsg.businessCode == 0) {
							//刷新商品列表信息
							loadData();
							window.layer.msg("删除成功");
						} else {
							//刷新商品列表信息
							loadData();
							window.layer.msg(businessMsg.businessNote);
						}
					});
				});
			} else {
				task.modal_alert("请至少选择一条数据记录");
			}
			//a标签的点击事件要加个返回值，false时禁用到点击时控件随机的链接跳转
			return false;
		});
	}
	
	/***********************************************前端商品列表排序*********************************/
	var goodsSortInit = function() {
		//先解除绑定，保证每次只绑定一次
		$(document).off('click',"#goods_sort").on('click',"#goods_sort",function() {
			common.ajax_request2('post','/api/seller/v1/goodsSortList',{},function($data,$code){
				if($code==200){
					$('#goodssortModal .bd').html(goodssort_tpl($data));
					$('#goodssortModal').modal('show');
				}
			});
		});
		//上调下调
		$(document).off('click',"#goodssortModal .bd a").on('click',"#goodssortModal .bd a",function() {
			var $this=$(this);
			var _pli=$this.parents('li');
			if($this.hasClass('up')){
				var _pliprev=_pli.prev();
				if(_pliprev.length>0){
					$(_pliprev).before(_pli);
				}else{
					window.layer.msg("已经是第一个了");
				}
			}else if($this.hasClass('down')){
				var _plinext=_pli.next();
				if(_plinext.length>0){
					$(_plinext).after(_pli);
				}else{
					window.layer.msg("已经是最后个了");
				}
			}
		});
		var _issubmit=false;
		$(document).off('click',"#goodssortModal .submitBtn").on('click',"#goodssortModal .submitBtn",function() {
			if(_issubmit){
				window.layer.msg("你不要一直点啊!");
				return;
			}
			var _goodsIds=[];
			$.each($('#goodssortModal .bd li'),function(index,data){
				_goodsIds.push($(this).attr('data-id'));
			});
			_issubmit=true;
			common.ajax_request2('post','/api/seller/v1/goodsSortUpdate',{goodsIds:_goodsIds.join(',')},function($data,$code){
				if($code==200){
					$('#goodssortModal').modal('hide');
				}
				_issubmit=false;
			});
		});
		
	}
	/***********************************************前端商品列表排序结束*********************************/
	
	
	/***********************************************地推二维码开始*********************************/
	// 商品列表上的地推二维码按钮
	$(document).on('click','.createCoreBtn',function(){
		var _orderbox=$(this).parents('.orderbox');
		var _labeltype=$(this).attr('data-labeltype');
		var _goodsid=_orderbox.find('.goods_single_edit_btn:first').attr('data-id');
		$('#codeModal .goodsimg>img').attr('src',_orderbox.find('.fm-goods-img>img').attr('src'));
		$('#codeModal .goodsinfo .big-title').html(_orderbox.find('p.maintitle').text());
		$('#codeModal .goodsinfo .small-title').html(_orderbox.find('p.subtitle').text());
		$('.codeGenerate').attr('data-id',_goodsid);
		$('.codeGenerate').attr('data-labeltype',_labeltype);
		if(_labeltype=='2'){
			$('#codeModal .codehouse').show();
		}else{
			$('#codeModal .codehouse').hide();
		}
		//清空之前选项
		$('.selectHouse').html('选择小区');
		$('.codeGenerate').removeAttr('data-commid');
		$(".saveImg").hide();
		$(".codeSubmit").hide();
		$("#outcode").empty();
		$('#codeurl').html('');
		
		// 重新加载小区
		housedata=undefined;
		if(_labeltype=='2'){
			common.ajax_request2('get','/api/seller/v1/queryCommunityByGoodsId',{goodsId:_goodsid},function($data,$code,$business){
				if($code==200){
					housedata=$data;
				}else{
					window.layer.msg($business.businessNote);
				}
			},false);
		}
		
		$('#codeModal').modal('show');
		
		//生成二维码
		//createcode();
	});

	//生成二维码
	$(document).off('click','.codeGenerate').on('click','.codeGenerate',function(){
		if((typeof $(this).attr('data-commid') == 'undefined' || $(this).attr('data-commid')=='') && $('.codeGenerate').attr('data-labeltype')=='2'){
			showhouseModal();
		}else{
			//生成二维码
			createcode();
			$(".saveImg").show();
			$(".codeSubmit").show();
		}
	});
	
	// 保存二维码
	$(document).on('click','.saveImg',function(){
		downloadimg();
	});
	
	// 生成二维码
	var createcode=function(){
		var _codeGenerate=$('#codeModal .codeGenerate:first');
		var outcodeurl;
		// 判断服务商品和销售商品
		if($('.codeGenerate').attr('data-labeltype')=='2' && (typeof _codeGenerate.attr('data-commid') != 'undefined' &&  _codeGenerate.attr('data-commid')!='')){
			outcodeurl=config.sysconfig().homeGiveMobileRoot+'dist/html/qcode_loading.html?dis_channel_id=0&count=1&id='+_codeGenerate.attr('data-id')+'&cid='+_codeGenerate.attr('data-commid');
		}else{
			outcodeurl=config.sysconfig().homeGiveMobileRoot+'dist/html/goods/detail.html?dis_channel_id=0&id='+_codeGenerate.attr('data-id');
		}
		
		$("#outcode").empty();
		$('#codeurl').html(outcodeurl);
		$("#outcode").qrcode({ 
//		    render: "table", //table方式 
	        render: "canvas", //canvas方式 
		    width: 140, //宽度 
		    height:140, //高度 
		    text: outcodeurl // 二维码内容
		});
		$("#outcodehide>canvas").remove();
		$("#outcodehide").qrcode({ 
//		    render: "table", //table方式 
	        render: "canvas", //canvas方式 
		    width: 500, //宽度 
		    height:500, //高度 
		    text: outcodeurl // 二维码内容
		});
		
	};
	
	// 下载二维码
	var downloadimg=function(){
		// help read url https://www.baidufe.com/item/65c055482d26ec59e27e.html
		var _canvas=$('#outcodehide>canvas').get(0);
		// 1 从canvas中直接提取图片元数据
		// 图片导出为 png 格式
		var type = 'png';
		var imgData = _canvas.toDataURL(type);
		
		// 2 将mime-type改为image/octet-stream，强制让浏览器直接download
		
		/**
		 * 获取mimeType
		 * @param  {String} type the old mime-type
		 * @return the new mime-type
		 */
		var _fixType = function(type) {
		    type = type.toLowerCase().replace(/jpg/i, 'jpeg');
		    var r = type.match(/png|jpeg|bmp|gif/)[0];
		    return 'image/' + r;
		};
		   
		// 加工image data，替换mime type
		imgData = imgData.replace(_fixType(type),'image/octet-stream');
		
		// 3 图片download到本地
		/**
		 * 在本地进行文件保存
		 * @param  {String} data     要保存到本地的图片数据
		 * @param  {String} filename 文件名
		 */
		var saveFile = function(data, filename){
		    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
		    save_link.href = data;
		    save_link.download = filename;
		   
		    var event = document.createEvent('MouseEvents');
		    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		    save_link.dispatchEvent(event);
		};
		   
		// 下载后的问题名
		var filename =$.trim($('#codeModal .goodsinfo .big-title').text())+'_' + (new Date()).getTime() + '.' + type;
		// download
		saveFile(imgData,filename);	
	};

	//选择小区
	$(document).off('click','.selectHouse').on('click','.selectHouse',function(){
		$('#houseModal>.modal-dialog .hd-search input').val('');
		showhouseModal();
	});
	
	// 显示小区数据
	var showhouseModal=function(){
		sethousedata();
		$('#houseModal').modal('show');
	};

	// 小区数据需要预加载数据
	var housedata;
		
	var sethousedata=function(search){
		var _house=$('#houseModal>.modal-dialog .houselist ul');
		_house.empty();
		if(typeof housedata != 'undefined'){
			$.each(housedata,function(index,data){
				if(typeof search !='undefined' && search!=''){
					if(data.community_name.indexOf(search)!=-1){
						_house.append('<li data-id="'+data.community_id+'" class="0on">'+data.community_name+'</li>');
					}
				}else{
					_house.append('<li data-id="'+data.community_id+'" class="0on">'+data.community_name+'</li>');
				}
			});
		}
	};
	
	// 输入框change
	$('#houseModal>.modal-dialog .hd-search input').bind('input propertychange', function() {
		var _txt=$(this).val();
		sethousedata(_txt);
	});
	
	//只能选择1个小区
	$(document).off('click','.houselist ul li').on('click','.houselist ul li',function(){
		$('.houselist ul li').removeClass("on");
		$(this).addClass("on");
	});
	
	//只能选择1个小区,按钮确定
	$(document).off('click','.oneSubmit').on('click','.oneSubmit',function(){
		var selectLi=$(".houselist ul").find(".on:first").html();
		$(".selectHouse").html(selectLi);
		$('.codeGenerate').attr('data-commid',$(".houselist ul").find(".on:first").attr('data-id'));
		$('#houseModal').modal('hide');
	});

	/***********************************************地推二维码结束*********************************/
	
	
	/*******************************************消息提示开始****************************************/
	
	/*//加载消息模板
	var _loadMessageTaskTPL = function() {
		var goods_msg_tpl = "";
		goods_msg_tpl = arttemplateUtil.template.compile($.setHTML('goods/templates/goods_message_tpl.html'));
		return goods_msg_tpl;
	}
	
	//点击消息提示按钮加载消息信息
	$(document).off('click','.mesInfo').on('click','.mesInfo',function(event){
		var $this = $(this);
		//获取商品id
		var _goodsid=$(this).parents('.orderbox').find('.chk:first').val();
		var _msgtpl = _loadMessageTaskTPL();
		var _msghtml = _msgtpl({"title":"商品id"+ _goodsid +"库存不足,即将下架，请尽快处理"});
		$("#msg_container_task").html(_msghtml);
		//取消事件冒泡  
	    event.stopPropagation();  
		messageDialog(this);
		//点击已处理按钮
		$(".okgo").off('click').on('click',function(){
			//调用修改该消息状态的接口，将消息状态改为已处理
			common.common_ajax_request('/api/seller/v1/getCommunityListById',{
				dpDate:$("#dp_data").html(),
				dpId:dpId
			}, false, function(data,code,msg){
				if(msg.businessCode==0){
					$this.hide();
			    	$('.mes-container').css('display','none');
				}else{
					window.layer.msg(msg.businessNote);
				}
			});
			$this.hide();
	    	$('.mes-container').css('display','none');
	    });
	});*/
	
	//消息提示
	$(document).off('click','.mesInfo').on('click','.mesInfo',function(event){
		var $this = $(this);
		//取消事件冒泡  
	    event.stopPropagation();  
	    msg_util.msgDialog(this,function(){
	    	loadData();
	    });
	});
	
	/*******************************************消息提示结束****************************************/
	var init = function() {
		initTpl();
		initGoodsPageList(); 
		goodsMulitIdDownShelveBtnClick();
		goodsSigleDownShelveBtnClick();
		goodsRecommendBtnClick("#goods_recommend_btn");
		goodsSearchBtnClick();
		resetBtnClick();
		goodsDeleteBtnClick();
		goodsSortInit();
		goodsCommon.loadConformTaskHtml();
		goodsCommon.checkAllOrNotClick();
		goodsCommon.checkBtnClick();		
		goodsCommon.goodsInventoryUpdateBtnClick();
		goodsCommon.goodsPriceUpdateBtnClick();
		goodsCommon.goodsSingleEditBtnClick();
		goodsCommon.goodsYFPriceUpdateBtnClick(".goods_yunfei_price_update_btn");
    }
	
    init();
});
